import New from '@/utils/new'

/**
 * 最大记录数量
 */
const MAX_COUNT = 30

export default class CameraRecordUtil {
  constructor(id, viewer) {
    this._id = id
    this._viewer = viewer
    this._records = []
    this._index = -1
  }

  static _instances = {}

  static getOrCreateUtil(id, viewer) {
    if (!this._instances[id]) {
      this._instances[id] = new CameraRecordUtil(id, viewer)
    }
    return this._instances[id]
  }

  get index() {
    return this._index
  }

  /**
   * 当前记录总数
   */
  get count() {
    return this._records.length
  }

  /**
   * 添加记录
   *
   * @param record Camera位置记录
   */
  add(record) {
    // debugger
    if (this.count === 0) {
      this._records.push(record)
      this._index += 1
    } else if (this.count < MAX_COUNT) {
      if (this._index === this.count - 1) {
        this._records.push(record)
        this._index += 1
      } else {
        this._records.splice(this._index + 1)
        this._records.push(record)
        this._index += 1
      }
    } else {
      this._records.splice(0, 1)
      this._records.push(record)
      this._index += 1
    }
  }

  /**
   * 前一个位置
   */
  previous() {
    // debugger
    if (this.count > 0 && this._index > 0) {
      this._index -= 1
      const position = this._records[this._index].position
      this._viewer.camera.flyTo({
        // destination: Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height),
        destination: new Cesium.Cartesian3(
          position.x,
          position.y,
          position.z
        ),
        // destination: this._records[this._index].position,
        orientation: this._records[this._index].orientation
      })
      New.$emit('cameraMovedByNavigation')
    } else {
      throw new Error('已经是第一个位置')
    }
  }

  /**
   * 后一个位置
   */
  next() {
    // debugger
    if (
      this.count > 0 &&
      this._index >= 0 &&
      this._index < this.count - 1
    ) {
      this._index += 1
      const position = this._records[this._index].position
      this._viewer.camera.flyTo({
        // destination: Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height),
        destination: new Cesium.Cartesian3(
          position.x,
          position.y,
          position.z
        ),
        // destination: this._records[this._index].position,
        orientation: this._records[this._index].orientation
      })
      New.$emit('cameraMovedByNavigation')
    } else {
      throw new Error('已经是最后一个位置')
    }
  }
}
